package com.mongodb.application.dao.user.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.mongodb.application.dao.user.UserDao;
import com.mongodb.application.entity.user.UserEntity;

@Repository("userDao")
public class UserDaoImpl implements UserDao{
	
	/**
     * 由springboot自动注入，默认配置会产生mongoTemplate这个bean
     */
    @Autowired
    private MongoTemplate mongoTemplate;
    
	@Override
	public List<UserEntity> findAll() {
		return mongoTemplate.findAll(UserEntity.class);
	}

	@Override
	public UserEntity getUser(String id) {
		UserEntity user = new UserEntity();
		try {
			user = mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), UserEntity.class);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("查询用户ID异常！");
		}
		return user;
	}

	@Override
	public void update(UserEntity user) {
		Criteria criteria = Criteria.where("_id").is(user.get_id());
        Query query = new Query(criteria);
        Update update = Update.update("name", user.getName());
        mongoTemplate.updateMulti(query, update, UserEntity.class);
	}

	@Override
	public void insert(UserEntity user) {
		mongoTemplate.insert(user);
	}

	@Override
	public void insertAll(List<UserEntity> users) {
		mongoTemplate.insertAll(users);
	}

	@Override
	public void remove(Integer id) {
		Criteria criteria = Criteria.where("_id").is(id);  
        Query query = new Query(criteria);
        mongoTemplate.remove(query,UserEntity.class);
	}

	@Override
	public List<UserEntity> findByPage(UserEntity user, Pageable pageable) {
		Query query = new Query();
        if (user != null && user.getName() != null) {
            //模糊查询
            query = new Query(Criteria.where("name").regex("^" + user.getName()));
        }
        List<UserEntity> list = mongoTemplate.find(query.with(pageable), UserEntity.class);
        return list;
	}

}
